/**
 *
 */
package com.tastesport.chat.processor;

import com.tastesport.chat.service.UserService;
import com.tastesport.chat.util.RedisUtil;
import com.tastesport.chat.util.SpringUtil;
import org.jim.common.ImSessionContext;
import org.jim.common.ImStatus;
import org.jim.common.packets.*;
import org.jim.server.command.handler.processor.login.LoginCmdProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;

import java.util.*;

/**
 * @author WChao
 *
 */
@Component
public class LoginServiceProcessor implements LoginCmdProcessor {

    private Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);

    @Autowired
    RedisUtil redisUtil;
    @Value("${custom-attr.redis.rootname}")
    String redisRoot;

    public List<Group> initFriends(User user) {
        List<Group> friends = new ArrayList<Group>();
        Group myFriend = new Group("我的好友");
        List<User> myFriendGroupUsers = new LinkedList<>();

        myFriend.setUsers(myFriendGroupUsers);
        friends.add(myFriend);
        return friends;
    }

    public String newToken() {
        return UUID.randomUUID().toString();
    }

    /**
     * doLogin方法注意：J-IM登陆命令是根据user是否为空判断是否登陆成功,
     *
     * 当登陆失败时设置user属性需要为空，相反登陆成功user属性是必须非空的;
     */
    @Override
    public LoginRespBody doLogin(LoginReqBody loginReqBody, ChannelContext channelContext) {
        UserService userService = SpringUtil.getBean(UserService.class);
        String userid = loginReqBody.getUserid();
        User user = userService.checkLogin(userid);
        LoginRespBody loginRespBody;
        if (user == null) {
            loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP, ImStatus.C10008);
        } else {
//            initGroups(user);
            user.setFriends(initFriends(user));
            loginRespBody = new LoginRespBody(Command.COMMAND_LOGIN_RESP, ImStatus.C10007, user);
        }
        return loginRespBody;
    }

    @Override
    public void onSuccess(ChannelContext channelContext) {
        logger.info("回调方法");
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        User user = imSessionContext.getClient().getUser();
    }

    @Override
    public boolean isProtocol(ChannelContext channelContext) {

        return true;
    }

    @Override
    public String name() {

        return "default";
    }
}
